package com.chilly.jdkNio.action.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * 使用JDK NIO 进行编程的案例: 群聊系统
 * 实现多人群聊
 * 服务器端: 可以检测用户上线，离线，并实现消息转发功能
 * 客户端：通过channel可以无阻塞发送消息给其他所有用户，同时可以接收其他用户发送的消息
 * 目的：进一步了解NIO非阻塞网络编程机制
 * Created by Chilly Cui on 2021/1/10.
 */
public class GroupChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //构造器
    //初始化工作
    public GroupChatServer() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听
    public void listen() {
        try {
            //循环处理
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false); //设置非阻塞

                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "上线");
                        }

                        if (key.isReadable()) {
                            //处理读（专门写方法）
                            readData(key);
                        }

                        iter.remove();//删除key，防止重复操作
                    }
                } else {
                    System.out.println("等待中......");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readData(SelectionKey key) {
        SocketChannel channel = null;

        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);

            //根据count的值做处理
            if (count > 0) {
                String msg = new String(buffer.array());
                //输出客户端发送的消息
                System.out.println("from client--->" + msg);

                //向其他客户端转发消息（去掉自己），给通道发
                sendInfoToOtherClients(msg, channel);

            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                System.out.println(channel.getRemoteAddress() + "离线");
                key.cancel(); //取消注册
                channel.close();//关闭通道
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

    //向其他客户端转发消息（去掉自己），给通道发
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中......");
        for (SelectionKey key : selector.keys()) { //循环向所有channel广播信息
            Channel targetChannel = key.channel();
            //System.out.println("targetChannel=" + targetChannel);
            //剔除发消息的客户端,排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 转型
                SocketChannel des = (SocketChannel) targetChannel;
                des.write(buffer);
            }
        }
    }


    public static void main(String[] args) {
        GroupChatServer chatServer = new GroupChatServer();
        chatServer.listen();
    }
}
